<template>
  <EChartsComponent :option="chartOption" />
</template>

<script setup lang="ts">
import { computed, watch } from "vue";
import EChartsComponent from "./EChartsComponent.vue";
import type { EChartsOption } from "echarts";

interface Props {
  buildingId: number;
}

const props = defineProps<Props>();

const chartConfigs = [
  { name: "PH值", key: "ph", color: "#ff6b6b", unit: "", yAxisIndex: 0 },
  {
    name: "水温(°C)",
    key: "temperature",
    color: "#4ecdc4",
    unit: "°C",
    yAxisIndex: 0,
  },
  {
    name: "溶解氧(mg/L)",
    key: "oxygen",
    color: "#45b7d1",
    unit: "mg/L",
    yAxisIndex: 0,
  },
  {
    name: "亚硝酸盐(mg/L)",
    key: "nitrite",
    color: "#f9ca24",
    unit: "mg/L",
    yAxisIndex: 1,
  },
  {
    name: "总盐(‰)",
    key: "salinity",
    color: "#6c5ce7",
    unit: "‰",
    yAxisIndex: 1,
  },
];

// 生成模拟数据
const generateWaterQualityData = (buildingId: number) => {
  const now = new Date();
  const data: Record<string, Array<{ time: string; value: number }>> = {};

  chartConfigs.forEach((config) => {
    data[config.key] = [];

    for (let i = 23; i >= 0; i--) {
      // 创建整点时间
      const time = new Date(now.getTime() - i * 60 * 60 * 1000);
      time.setMinutes(0, 0, 0); // 设置为整点
      let value = 0;

      // 根据楼栋ID和参数类型生成不同的基础值
      const baseOffset = (buildingId - 1) * 0.1;

      switch (config.key) {
        case "temperature":
          value = 26 + Math.sin(i * 0.3) * 2 + Math.random() * 1 + baseOffset;
          break;
        case "ph":
          value =
            7.5 +
            Math.sin(i * 0.2) * 0.3 +
            Math.random() * 0.2 +
            baseOffset * 0.1;
          break;
        case "salinity":
          value = 15 + Math.sin(i * 0.4) * 1 + Math.random() * 0.5 + baseOffset;
          break;
        case "oxygen":
          value =
            6 +
            Math.sin(i * 0.5) * 0.8 +
            Math.random() * 0.3 +
            baseOffset * 0.5;
          break;
        case "nitrite":
          value =
            0.3 +
            Math.sin(i * 0.6) * 0.15 +
            Math.random() * 0.1 +
            baseOffset * 0.01;
          break;
      }

      data[config.key].push({
        time: time.toLocaleTimeString("zh-CN", {
          hour: "2-digit",
          minute: "2-digit",
        }),
        value: Number(value.toFixed(2)),
      });
    }
  });

  return data;
};

// 生成合并图表选项的计算属性
const chartOption = computed((): EChartsOption => {
  const data = generateWaterQualityData(props.buildingId);

  // 获取时间轴数据（所有参数的时间都相同）
  const timeData = data[chartConfigs[0].key].map((item) => item.time);

  // 创建Y轴配置 - 参考 aquaculture-dashboard2.vue 的简化方式
  const yAxes = [
    {
      type: "value" as const,
      nameTextStyle: { color: "#0efcff", fontSize: 10 },
      axisLine: {
        show: true,
        lineStyle: { color: "#0efcff", width: 3, type: "solid" as const },
      },
      axisLabel: {
        color: "#0efcff",
        fontSize: 10,
        fontWeight: "bold" as const,
      },
      splitLine: { lineStyle: { color: "rgba(14, 252, 255, 0.2)" } },
    },
    {
      type: "value" as const,
      nameTextStyle: { color: "#0efcff", fontSize: 10 },
      axisLine: {
        show: true,
        lineStyle: { color: "#0efcff", width: 3, type: "solid" as const },
      },
      axisLabel: {
        color: "#0efcff",
        fontSize: 10,
        fontWeight: "bold" as const,
      },
      splitLine: { show: false },
    },
  ];

  // 创建系列数据
  const series = chartConfigs.map((config) => ({
    name: config.name,
    type: "line" as const,
    yAxisIndex: config.yAxisIndex,
    data: data[config.key].map((item) => item.value),
    smooth: true,
    lineStyle: {
      color: config.color,
      width: 2,
    },
    itemStyle: {
      color: config.color,
    },
    symbol: "circle",
    symbolSize: 4,
  }));

  return {
    backgroundColor: "transparent",
    grid: { left: 30, right: 30, top: 60, bottom: 30 },
    legend: {
      data: chartConfigs.map((config) => config.name),
      textStyle: {
        color: "#0efcff",
        fontSize: 12,
      },
      top: 0,
      left: 0,
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0, 0, 0, 0.8)",
      borderColor: "#0efcff",
      borderWidth: 1,
      textStyle: {
        color: "#0efcff",
        fontSize: 12,
      },
      formatter: (params: any) => {
        const paramArray = Array.isArray(params) ? params : [params];
        let result = `${paramArray[0].axisValue}<br/>`;
        paramArray.forEach((param: any) => {
          const config = chartConfigs.find((c) => c.name === param.seriesName);
          const unit = config?.unit || "";
          result += `${param.marker}${param.seriesName}: ${param.value}${unit}<br/>`;
        });
        return result;
      },
    },
    xAxis: {
      type: "category",
      data: timeData,
      axisLine: {
        show: true,
        lineStyle: { color: "#0efcff", width: 3, type: "solid" },
      },
      axisLabel: {
        color: "#0efcff",
        fontSize: 10,
        interval: 2,
        margin: 8,
        fontWeight: "bold",
      },
    },
    yAxis: yAxes,
    series: series,
  };
});

// 监听楼栋变化，重新生成图表选项
watch(
  () => props.buildingId,
  () => {
    // 计算属性会自动重新计算
  },
  { immediate: false }
);
</script>
